import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

import { resetRouter, asyncroutes, anyroutes, baseroutes } from '@/router'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    buttons: [], // 可以操作的按钮的标记
    routes: [], // 用户可以看到的路由
    roles: [], // 用户的角色
    resasyncroutes: [], // 用户可以看的路由
    constantRoutes: [] // 最后需要展示的路由
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERINFO: (state, userinfo) => {
    state.avatar = userinfo.avatar
    state.name = userinfo.name
    state.buttons = userinfo.buttons
    state.routes = userinfo.routes
    state.roles = userinfo.roles
  },
  SET_RESROUTES: (state, resasyncroutes) => {
    // 合并常量路由和任意路由
    state.resasyncroutes = resasyncroutes
    // 将计算出的需要展示的路由合并到常量路由中去
    state.constantRoutes = baseroutes.concat(state.resasyncroutes, anyroutes)
    router.addRoutes(state.constantRoutes)
  }
}

// 筛选路由
function selectroutes(asyncroutes, routes) {
  return asyncroutes.filter(item => {
    if (routes.indexOf(item.name) !== -1) {
      // 如果存在子路由的话
      if (item.children && item.children.length) {
        item.children = selectroutes(item.children, routes)
      }
      return true
    }
  })
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    const res = await login({ username: username.trim(), password: password })
    if (res.code === 20000) {
      commit('SET_TOKEN', res.data.token)
      setToken(res.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('错误'))
    }
  },

  // get user info
  // 返回用户信息
  async getInfo({ commit, state }) {
    const res = await getInfo(state.token)
    if (res.code === 20000) {
      console.log(res.data.routes) // 用户可以看到的菜单
      //   buttons 可以操作的按钮
      if (!res.data) {
        return Promise.reject('Verification failed, please Login again.')
      }
      commit('SET_USERINFO', res.data)
      commit('SET_RESROUTES', selectroutes(asyncroutes, res.data.routes))
      return 'ok'
    } else {
      return Promise.reject(new Error('错误'))
    }
  },

  // user logout
  async logout({ commit, state }) {
    const res = await logout(state.token)
    if (res.code === 20000) {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      return 'ok'
    } else {
      return Promise.reject(new Error('错误'))
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
